﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseCheckcard;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.BaseData.Entitys.Dto.QmsBaseCheckcardsample;
using SHZY.BaseData.Entitys.Dto.QmsBaseCheckcarddetail;
using SHZY.BaseData.Entitys.Entity;
using Newtonsoft.Json.Linq;
using SHZY.BaseData.Entitys.Dto.CheckcardMaterial;
using Org.BouncyCastle.Crypto;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：检卡信息.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Checkcard", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseCheckcardService : IQmsBaseCheckcardService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseCheckcardEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseCheckcardService"/>类型的新实例.
    /// </summary>
    public QmsBaseCheckcardService(
        ISqlSugarRepository<QmsBaseCheckcardEntity> qmsBaseCheckcardRepository,
        ISqlSugarClient context,
        IUserManager userManager,
        IQmsBaseCheckcardsampleService qmsBaseCheckcardsampleService
        )
    {
        _repository = qmsBaseCheckcardRepository;
        _db = context.AsTenant();
        _userManager = userManager;
    }

    /// <summary>
    /// 获取检卡信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseCheckcardInfoOutput>();
    }

    /// <summary>
    /// 获取检卡明细信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("Detail/{id}")]
    public async Task<dynamic> GetDetail(string id)
    {
        var qmsBaseCheckcardInfoOutput = (await _repository.FirstOrDefaultAsync(x => x.Id == id && x.DeleteMark == null)).Adapt<QmsBaseCheckcardInfoOutput>();

        var qmsBaseCheckcardsampleInfoOutputList = (await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().Where(x => x.CheckGuid == id && x.DeleteMark == null).ToListAsync()).Adapt<List<QmsBaseCheckcardsampleInfoOutput>>();
        foreach (var item in qmsBaseCheckcardsampleInfoOutputList)
        {
            var qmsBaseCheckcarddetailInfoOutputList = (await _repository.Context.Queryable<QmsBaseCheckcarddetailEntity>().Where(x => x.SampleId == item.id && x.DeleteMark == null).OrderBy(x => x.Sort, OrderByType.Asc).ToListAsync()).Adapt<List<QmsBaseCheckcarddetailInfoOutput>>();
            item.children = qmsBaseCheckcarddetailInfoOutputList;
        }
        if (qmsBaseCheckcardsampleInfoOutputList?.Count > 0)
        {
            qmsBaseCheckcardInfoOutput.children = qmsBaseCheckcardsampleInfoOutputList;
        }
        var qmsBaseCheckcardmaterialList = await _repository.Context.Queryable<QmsBaseCheckcardmaterialEntity, QmsBaseMaterialEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.MaterialCode == b.Code))
            .Where((a, b) => a.ParentId == id && a.DeleteMark == null)
            .OrderBy(a => a.CreatorTime, OrderByType.Asc)
            .Select((a, b) => new QmsBaseCheckcardmaterialInfoOutput
            {
                id = a.Id,
                parentId = a.ParentId,
                materialCode = a.MaterialCode,
                materialDes = b.Name,
                enabledMark = a.EnabledMark
            })
            .ToListAsync();
        qmsBaseCheckcardInfoOutput.materialList = qmsBaseCheckcardmaterialList;

        return qmsBaseCheckcardInfoOutput;
    }

    /// <summary>
    /// 获取所有检卡信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.CreatorTime).ToListAsync();
        return new { list = data.Adapt<List<QmsBaseCheckcardInfoOutput>>() };

    }


    /// <summary>
    /// 获取检卡信息列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseCheckcardListQueryInput input)
    {

        var queryable = _repository.Context.Queryable<QmsBaseCheckcardEntity, QmsBaseMaterialEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.MaterialCode == b.Code))
            .WhereIF(!string.IsNullOrEmpty(input.name), (a, b) => a.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.business), a => a.Business.Contains(input.business))
            .WhereIF(!string.IsNullOrEmpty(input.remarks), a => a.Remarks.Contains(input.remarks))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.MaterialCode.Contains(input.keyword) || a.Business.Contains(input.keyword) || a.Remarks.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .Select((a, b) => new QmsBaseCheckcardListOutput
            {
                id = a.Id,
                name = a.Name,
                materialCode = a.MaterialCode,
                materialDes = b.Name,
                business = a.Business,
                customParameters = a.CustomParameters,
                remarks = a.Remarks,
                enabledMark = a.EnabledMark
            }).MergeTable();

        if (!string.IsNullOrEmpty(input.materialCode))
        {
            var list = await _repository.Context.Queryable<QmsBaseCheckcardmaterialEntity>().Where(x => x.MaterialCode == input.materialCode && x.DeleteMark == null).Select(x => x.ParentId).ToListAsync();
            queryable.Where(a => list.Contains(a.id));
        }

        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseCheckcardListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建检卡信息.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseCheckcardCrInput input)
    {
        //if (await _repository.AnyAsync(x => x.MaterialCode == input.materialCode && x.DeleteMark == null))
        //    throw Oops.Oh("物料不能重复维护检卡");

        var entity = input.Adapt<QmsBaseCheckcardEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取检卡信息无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseCheckcardListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseCheckcardEntity, QmsBaseMaterialEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.MaterialCode == b.Code))
             .WhereIF(!string.IsNullOrEmpty(input.name), (a, b) => a.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.materialCode), a => a.MaterialCode.Contains(input.materialCode))
            .WhereIF(!string.IsNullOrEmpty(input.business), a => a.Business.Contains(input.business))
            .WhereIF(!string.IsNullOrEmpty(input.remarks), a => a.Remarks.Contains(input.remarks))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.MaterialCode.Contains(input.keyword) || a.Business.Contains(input.keyword) || a.Remarks.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), a => a.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        var data = await queryable.Select((a, b) => new QmsBaseCheckcardListOutput
        {
            id = a.Id,
            name = a.Name,
            materialCode = a.MaterialCode,
            materialDes = b.Name,
            business = a.Business,
            customParameters = a.CustomParameters,
            remarks = a.Remarks,
            enabledMark = a.EnabledMark
        }).ToListAsync();
        return data;
    }

    /// <summary>
    /// 导出检卡信息.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseCheckcardListQueryInput input)
    {
        var exportData = new List<QmsBaseCheckcardListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseCheckcardListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"名称\",\"field\":\"name\"},{\"value\":\"物料编码\",\"field\":\"materialCode\"},{\"value\":\"适用业务:业务标准（过程检、抽检等）\",\"field\":\"business\"},{\"value\":\"⾃定义参数\",\"field\":\"customParameters\"},{\"value\":\"备注\",\"field\":\"remarks\"},{\"value\":\"有效标志0无效 1有效\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "检卡信息.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseCheckcardListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除检卡信息.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseCheckcardEntity>().In(it => it.Id, ids).ToListAsync();
        foreach (var entity in entitys)
        {
            Delete(entity.Id);
        }
    }

    /// <summary>
    /// 更新检卡信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseCheckcardUpInput input)
    {
        //if (await _repository.AnyAsync(x => x.MaterialCode == input.materialCode && x.DeleteMark == null && x.Id != input.id))
        //    throw Oops.Oh("物料不能重复维护检卡");
        var entity = input.Adapt<QmsBaseCheckcardEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 批量保存检卡信息（id字段为空是新增，不为空是更新）.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("submit")]
    public async Task Submit([FromBody] QmsBaseCheckcardUpInput input)
    {
        try
        {
            // 开启事务
            _db.BeginTran();
            var entity = input.Adapt<QmsBaseCheckcardEntity>();
            //id为空则新增，反之更新
            if (string.IsNullOrEmpty(input.id))
            {
                //if (await _repository.AnyAsync(x => x.MaterialCode == input.materialCode && x.DeleteMark == null))
                //    throw Oops.Oh("物料不能重复维护检卡");
                var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOk < 1)
                    throw Oops.Oh(ErrorCode.COM1000);
            }
            else
            {
                //if (await _repository.AnyAsync(x => x.MaterialCode == input.materialCode && x.DeleteMark == null && x.Id != input.id))
                //    throw Oops.Oh("物料不能重复维护检卡");
                var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                if (!isOk)
                    throw Oops.Oh(ErrorCode.COM1001);
            }

            foreach (var checkCardSampleItem in input.children)
            {
                checkCardSampleItem.checkGuid = entity.Id;
                //id为空则新增，反之更新
                if (!string.IsNullOrEmpty(checkCardSampleItem.insertFlag))
                {
                    if (await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().AnyAsync(x => x.CheckGuid == checkCardSampleItem.checkGuid && x.SamplingType == checkCardSampleItem.samplingType && x.DeleteMark == null))
                        throw Oops.Oh("检卡不能重复维护抽样方案");
                    var qmsBaseCheckcardsampleEntity = checkCardSampleItem.Adapt<QmsBaseCheckcardsampleEntity>();
                    var isOkInsertable = await _repository.Context.Insertable(qmsBaseCheckcardsampleEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                    if (isOkInsertable < 1)
                        throw Oops.Oh(ErrorCode.COM1000);
                    foreach (var checkCardDetailItem in checkCardSampleItem.children)
                    {
                        checkCardDetailItem.sampleId = qmsBaseCheckcardsampleEntity.Id;
                        if (await _repository.Context.Queryable<QmsBaseCheckcarddetailEntity>().AnyAsync(x => x.SampleId == checkCardDetailItem.sampleId && x.InnspectionName == checkCardDetailItem.innspectionName && x.InnspectionEntry == checkCardDetailItem.innspectionEntry && x.DeleteMark == null))
                            throw Oops.Oh("检验项目与条目不能重复维护");
                        var qmsBaseCheckcarddetailEntity = checkCardDetailItem.Adapt<QmsBaseCheckcarddetailEntity>();
                        isOkInsertable = await _repository.Context.Insertable(qmsBaseCheckcarddetailEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                        if (isOkInsertable < 1)
                            throw Oops.Oh(ErrorCode.COM1000);
                    }
                }
                else
                {
                    if (await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().AnyAsync(x => x.CheckGuid == checkCardSampleItem.checkGuid && x.SamplingType == checkCardSampleItem.samplingType && x.DeleteMark == null && x.Id != checkCardSampleItem.id))
                        throw Oops.Oh("检卡不能重复维护抽样方案");
                    var qmsBaseCheckcardsampleEntity = checkCardSampleItem.Adapt<QmsBaseCheckcardsampleEntity>();
                    var isOk = await _repository.Context.Updateable(qmsBaseCheckcardsampleEntity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                    if (!isOk)
                        throw Oops.Oh(ErrorCode.COM1001);
                    foreach (var checkCardDetailItem in checkCardSampleItem.children)
                    {
                        checkCardDetailItem.sampleId = qmsBaseCheckcardsampleEntity.Id;
                        //id为空则新增，反之更新
                        if (!string.IsNullOrEmpty(checkCardDetailItem.insertFlag))
                        {
                            if (await _repository.Context.Queryable<QmsBaseCheckcarddetailEntity>().AnyAsync(x => x.SampleId == checkCardDetailItem.sampleId && x.InnspectionName == checkCardDetailItem.innspectionName && x.InnspectionEntry == checkCardDetailItem.innspectionEntry && x.DeleteMark == null))
                                throw Oops.Oh("检验项目与条目不能重复维护");
                            var qmsBaseCheckcarddetailEntity = checkCardDetailItem.Adapt<QmsBaseCheckcarddetailEntity>();
                            var isOkInsertable = await _repository.Context.Insertable(qmsBaseCheckcarddetailEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                            if (isOkInsertable < 1)
                                throw Oops.Oh(ErrorCode.COM1000);
                        }
                        else
                        {
                            if (await _repository.Context.Queryable<QmsBaseCheckcarddetailEntity>().AnyAsync(x => x.SampleId == checkCardDetailItem.sampleId && x.InnspectionName == checkCardDetailItem.innspectionName && x.InnspectionEntry == checkCardDetailItem.innspectionEntry && x.DeleteMark == null && x.Id != checkCardDetailItem.id))
                                throw Oops.Oh("检验项目与条目不能重复维护");
                            var qmsBaseCheckcarddetailEntity = checkCardDetailItem.Adapt<QmsBaseCheckcarddetailEntity>();
                            isOk = await _repository.Context.Updateable(qmsBaseCheckcarddetailEntity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                            if (!isOk)
                                throw Oops.Oh(ErrorCode.COM1001);
                        }
                    }
                }
            }
            // 维护物料分配信息
            if (input.materialList != null)
            {
                foreach (var item in input.materialList)
                {
                    //id为空则新增，反之更新
                    if (string.IsNullOrEmpty(item.id))
                    {
                        if (await _repository.Context.Queryable<QmsBaseCheckcardmaterialEntity>().AnyAsync(x => x.ParentId == entity.Id && x.MaterialCode == item.materialCode && x.DeleteMark == null))
                            throw Oops.Oh("物料添加重复，请确认");

                        var qmsBaseCheckcardmaterialEntity = item.Adapt<QmsBaseCheckcardmaterialEntity>();
                        qmsBaseCheckcardmaterialEntity.ParentId = entity.Id;
                        var isOk = await _repository.Context.Insertable(qmsBaseCheckcardmaterialEntity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                        if (isOk < 1)
                            throw Oops.Oh(ErrorCode.COM1000);
                    }
                    else
                    {
                        if (await _repository.Context.Queryable<QmsBaseCheckcardmaterialEntity>().AnyAsync(x => x.Id != item.id && x.ParentId == entity.Id && x.MaterialCode == item.materialCode && x.DeleteMark == null))
                            throw Oops.Oh("物料添加重复，请确认");
                        var qmsBaseCheckcardmaterialEntity = item.Adapt<QmsBaseCheckcardmaterialEntity>();
                        qmsBaseCheckcardmaterialEntity.ParentId = entity.Id;
                        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
                        if (!isOk)
                            throw Oops.Oh(ErrorCode.COM1001);
                    }
                }
            }
            // 关闭事务
            _db.CommitTran();

        }
        catch (Exception ex)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ex.Message);
        }

    }


    /// <summary>
    /// 复制检卡明细信息.
    /// </summary>
    /// <param name="fromId">来源对象ID.</param>
    /// <param name="toId">覆盖对象ID.</param>
    /// <returns></returns>
    [HttpPost("copy/{fromId}/{toId}")]
    public async Task Copy(string fromId, string toId)
    {
        try
        {
            // 开启事务
            _db.BeginTran();
            //先删除当前检卡的抽样信息和检验项目信息
            var checkcardsampleList = await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().Where(x => x.CheckGuid == toId).ToListAsync();
            foreach (var item in checkcardsampleList)
            {
                var isOk1 = await _repository.Context.Updateable<QmsBaseCheckcarddetailEntity>().SetColumns(it => new QmsBaseCheckcarddetailEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(x => x.SampleId == item.Id).ExecuteCommandHasChangeAsync();
                if (!isOk1)
                    throw Oops.Oh(ErrorCode.COM1002);
            }
            var isOk2 = await _repository.Context.Updateable<QmsBaseCheckcardsampleEntity>().SetColumns(it => new QmsBaseCheckcardsampleEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.CheckGuid == toId).ExecuteCommandHasChangeAsync();
            if (!isOk2)
                throw Oops.Oh(ErrorCode.COM1002);

            //查询复制信息并插入到当前检卡
            //1.查询抽样信息
            var newCheckcardsampleList = await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().Where(x => x.CheckGuid == fromId && x.DeleteMark == null).ToListAsync();
            foreach (var checkcardsample in newCheckcardsampleList)
            {
                //2.查询检验项目信息
                var newCheckcarddetailList = await _repository.Context.Queryable<QmsBaseCheckcarddetailEntity>().Where(x => x.SampleId == checkcardsample.Id && x.DeleteMark == null).ToListAsync();

                //插入抽样信息
                checkcardsample.CheckGuid = toId;//替换成当前检卡的Id
                var isOk3 = await _repository.Context.Insertable(checkcardsample).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOk3 < 1)
                    throw Oops.Oh(ErrorCode.COM1000);

                foreach (var checkcarddetail in newCheckcarddetailList)
                {
                    //插入检验项目信息
                    checkcarddetail.SampleId = checkcardsample.Id;//替换成新插入的抽样id
                    var isOk4 = await _repository.Context.Insertable(checkcarddetail).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                    if (isOk4 < 1)
                        throw Oops.Oh(ErrorCode.COM1000);
                }

            }
            // 查询复制物料分配信息
            var qmsBaseCheckcardmaterialList = await _repository.Context.Queryable<QmsBaseCheckcardmaterialEntity>().Where(a => a.ParentId == fromId && a.DeleteMark == null)
           .OrderBy(a => a.CreatorTime, OrderByType.Asc).ToListAsync();
            foreach (var checkcardmaterial in qmsBaseCheckcardmaterialList)
            {
                checkcardmaterial.ParentId = toId;
                var isOk = await _repository.Context.Insertable(checkcardmaterial).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOk < 1)
                    throw Oops.Oh(ErrorCode.COM1000);
            }

            // 关闭事务
            _db.CommitTran();

        }
        catch (Exception ex)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ex.Message);
        }

    }

    /// <summary>
    /// 删除检卡信息.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        try
        {
            // 开启事务
            _db.BeginTran();
            var isOk = await _repository.Context.Updateable<QmsBaseCheckcardEntity>().SetColumns(it => new QmsBaseCheckcardEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
            if (!isOk)
                throw Oops.Oh(ErrorCode.COM1002);

            // 删除抽样方案
            var checkcardsampleList = await _repository.Context.Queryable<QmsBaseCheckcardsampleEntity>().Where(x => x.CheckGuid == id).ToListAsync();
            foreach (var checkcardsample in checkcardsampleList)
            {

                var isOk1 = await _repository.Context.Updateable<QmsBaseCheckcarddetailEntity>().SetColumns(it => new QmsBaseCheckcarddetailEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(x => x.SampleId == checkcardsample.Id).ExecuteCommandHasChangeAsync();

                var isOk2 = await _repository.Context.Updateable<QmsBaseCheckcardsampleEntity>().SetColumns(it => new QmsBaseCheckcardsampleEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(x => x.Id == checkcardsample.Id).ExecuteCommandHasChangeAsync();
            }

            // 删除物料
            var isOk3 = await _repository.Context.Updateable<QmsBaseCheckcardmaterialEntity>().SetColumns(it => new QmsBaseCheckcardmaterialEntity()
            {
                DeleteTime = DateTime.Now,
                DeleteMark = 1,
                DeleteUserId = _userManager.UserId
            }).Where(x => x.ParentId == id).ExecuteCommandHasChangeAsync();

            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception)
        {
            // 回滚事务
            _db.RollbackTran();

            throw Oops.Oh(ErrorCode.COM1002);
        }
    }

    /// <summary>
    /// 删除检卡物料分配信息.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("material/{id}")]
    public async Task DeleteMaterial(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBaseCheckcardmaterialEntity>().SetColumns(it => new QmsBaseCheckcardmaterialEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }
}